import { useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { Input, PageContainer, Picker, Switch, View } from "@tarojs/components";
import { useReactive, useSetState, useUpdateEffect } from "ahooks";
import pick from "lodash-es/pick";
import dayjs from "dayjs";

import Page from "@/components/common/Page";
import ByCell from "@/components/ui/ByCell";
import ByIcon from "@/components/ui/ByIcon";
import Uploader from "@/components/app/Uploader";
import ByButton from "@/components/ui/ByButton";
import ByCellGroup from "@/components/ui/ByCellGroup";
import ByImageGroup from "@/components/ui/ByImageGroup";
import TagRadioGroup from "@/components/app/TagRadioGroup";

import useForm from "@/hooks/useForm";
import ApiInspection from "@/api/inspection";
import PopupMember from "@/components/app/PopupMember";
import { pickTransMap } from "@/utils";

type FormModelInspection = {
  /**
   * 巡检名称
   */
  inspectionName: string;
  /**
   * 巡检内容
   */
  inspectionContent: string;
  intentCustomerId: number;
  remark: string;
  /**
   * 是否可见（业主？）
   */
  isCanSee: boolean;
  /**
   * 是否有图片
   */
  isPicture: Boolean;
  picList: string[];
  /**
   * 是否合格
   */
  isQualified: boolean;
  /**
   * 巡检日期
   */
  inspectionDate: string;
  /**
   * 不合格数量
   */
  unqualifiedNum: number;
};

type FormModelDetailListItem = {
  _id: number;

  /**
   * 问题类型
   */
  type: string;
  description: string;
  remark: string;

  /**
   * 负责人ID
   */
  headerId: number;
  /**
   * 负责人姓名
   */
  headerName: string;
  /**
   * 供应商ID
   */
  supplyId: number;
  /**
   * 供应商Code
   */
  supplyCode: string;
  /**
   * 供应商名称
   */
  supplyName: string;
  /**
   *  是否整改
   */
  isRectification: boolean;
  /**
   * 整改日期
   */
  requaireProcessDate: string;

  picList: {
    /**
     * 图片路径
     */
    picture: string;
  }[];
};

type FormModel = {
  inspection: FormModelInspection;
  detailList: FormModelDetailListItem[];
};

const CellProps = {
  labelWidth: "6em",
  border: true,
};

const questionTypes = [{ label: "质量" }, { label: "形象" }, { label: "其他" }];

const getDetailItem = (intentCustomerId) => {
  return {
    _id: new Date().getTime(),

    inspectionId: undefined,

    // 类型
    type: "",

    // 描述
    description: "",

    // 意向客户ID
    intentCustomerId,

    // 备注
    remark: "",

    // 是否整改
    isRectification: false,

    //  整改时间
    requaireProcessDate: "",

    // 整改责任人和对应ID
    headerName: "",
    headerId: undefined,

    supplyId: undefined,
    supplyCode: "",
    supplyName: "",

    isPicture: false,

    /**
     * {picture: string}
     */
    picList: [],
  } as unknown as FormModelDetailListItem;
};

const TaskItems = ({
  nodeId,
  index,
  source,
  onDelete,
  onChange,
  onPicker,
}: {
  nodeId: string;
  index: number;
  source: FormModel["detailList"][number];
  onDelete: () => void;
  onChange: (newModel: any) => void;
  onPicker: () => void;
}) => {
  const { picList } = source;

  const updatePics = (res) => {
    const list = res.map((picture) => ({
      picture,
      isCanView: true,
      isUpload: true,
    }));
    onChange({
      picList: picList.concat(list),
    });
  };

  const deletePic = (_, index) => {
    picList.splice(index, 1);
    onChange({ picList: [...picList] });
  };

  //  string[]
  const pics = picList.map(({ picture }) => picture);
  const picLength = pics.length;

  return (
    <>
      <ByCell
        size="small"
        label={`第${index + 1}项`}
        nextIcon={
          <ByIcon name="Delete" className="text-error" onClick={onDelete} />
        }
      />

      <ByCellGroup className="mb-4" id={nodeId}>
        <ByCell label="问题类型" requierd {...CellProps}>
          <TagRadioGroup
            options={questionTypes}
            value={[source.type]}
            onChange={(e) => onChange({ type: e[0] })}
          />
        </ByCell>

        <ByCell label="描述" {...CellProps}>
          <Input
            placeholder="输入问题描述"
            value={source.description}
            onInput={(e) => onChange({ description: e.detail.value })}
          />
        </ByCell>

        <ByCell
          vertical
          label="问题拍照"
          tip={picLength > 0 ? picLength + `张` : ""}
          {...CellProps}
        >
          {/* 添减图片 要及时更新 isPicture 状态 */}
          <ByImageGroup
            urls={pics}
            showDelete
            onChange={deletePic}
            slotFooter={<Uploader size={140} onSuccess={updatePics} />}
          />
        </ByCell>

        <ByCell label="整改通知" {...CellProps}>
          <Switch
            checked={source.isRectification}
            onChange={({ detail }) =>
              onChange({ isRectification: detail.value })
            }
          />
        </ByCell>

        {source.isRectification && (
          <>
            <ByCell
              {...CellProps}
              requierd
              label="整改责任人"
              nextIcon={<ByIcon name="PlusCirlce" size={32} />}
              onClick={onPicker}
            >
              <Input
                disabled
                value={source.supplyName || source.headerName}
                placeholder="请选择整改责任人"
                className="w-full"
              />
            </ByCell>

            <Picker
              mode="date"
              start={dayjs().format("YYYY-MM-DD")}
              value={source.requaireProcessDate}
              onChange={({ detail }) =>
                onChange({ requaireProcessDate: detail.value })
              }
            >
              <ByCell
                {...CellProps}
                requierd
                label="整改时间"
                nextIcon={<ByIcon name="Calendar" size={32} />}
              >
                <Input
                  disabled
                  placeholder="选择要求整改时间"
                  value={source.requaireProcessDate}
                />
              </ByCell>
            </Picker>
          </>
        )}
      </ByCellGroup>
    </>
  );
};

const rules = {
  inspection: {
    type: "object",
    required: true,
    fields: {
      // inspectionName: {
      //   type: "string",
      //   required: true,
      //   message: "请输入巡检名称",
      // },
      inspectionContent: {
        type: "string",
        required: true,
        message: "请输入巡检内容",
      },
    },
  },
  detailList: {
    type: "array",
    defaultField: {
      type: "object",
      validator: (rule, value, callback) => {
        const prefix = `请选择第${+rule.field + 1}项`;

        if (!value.type) {
          return callback(new Error(`${prefix}问题类型`));
        }

        if (value.isRectification) {
          if (!value.headerId && !value.supplyId) {
            return callback(new Error(`${prefix}整改负责人`));
          }

          if (!value.requaireProcessDate) {
            return callback(new Error(`${prefix}整改时间`));
          }
        }

        callback();
      },

      // fields: {
      //   type: { type: "string", required: true, message: "请输入问题类型" },
      //   requaireProcessDate: { validator, message: "请选择整改日期" },
      //   requaireProcessDate: { validator, message: "请选择整改日期" },
      // },
    },
  },
};

export default () => {
  const { params } = useRouter();
  const intentCustomerId = Number(params.intentCustomerId);

  const [model, setModel] = useSetState<FormModelInspection>({
    inspectionDate: dayjs().format("YYYY-MM-DD"),
    intentCustomerId,
    remark: "",
    picList: [],
    isCanSee: false,
  } as any);

  // 不合格列表
  const detailList = useReactive<FormModelDetailListItem[]>([]);

  // 创建日常巡检
  const {
    loading,
    model: formModel,
    setModel: setFormModel,
    submit,
  } = useForm<FormModel>(ApiInspection.inspectionCreate, {
    // @ts-expect-error
    rules,

    onSuccess() {
      Taro.showToast({ title: "创建成功！" });

      setTimeout(() => {
        // 先返回列表页
        Taro.navigateBack({ delta: 1 });
      });
    },
  });

  useUpdateEffect(() => {
    submit().catch((errors) => {
      const matches = errors[0].field.match(/detailList\.(\d+)/);

      if (matches) {
        const index = matches[1];
        Taro.pageScrollTo({
          selector: "#tast_item_node_" + index,
        });
      }
    });
  }, [formModel]);

  // 总提交按钮
  const handleSubmit = () => {
    setFormModel({
      detailList,

      inspection: {
        ...model,
        isPicture: model.picList.length > 0,
        isQualified: detailList.length === 0,
        unqualifiedNum: detailList.length,
      },
    });
  };

  // 添加巡检项目
  const addItem = () => {
    detailList.push(getDetailItem(intentCustomerId));
  };

  // 删除巡检项
  const handleDeleteItem = async (index: number) => {
    const { confirm } = await Taro.showModal({ title: "确定删除该项？" });
    if (confirm) {
      detailList.splice(index, 1);
    }
  };

  // 更新巡检项
  const handleChangeItem = (
    index,
    newData: Partial<FormModelDetailListItem>
  ) => {
    detailList[index] = {
      ...detailList[index],
      ...newData,
    };
  };

  const [selectedIndex, setSeletedIndex] = useState<number>(-1);

  const handleConfirm = (selectedData, type) => {
    let obj =
      type === "supplier"
        ? pick(selectedData, ["supplyId", "supplyName", "supplyCode"])
        : pickTransMap(selectedData, {
          userId: "headerId",
          userName: "headerName",
        });

    handleChangeItem(selectedIndex, {
      supplyId: undefined,
      supplyName: "",
      supplyCode: "",
      headerId: undefined,
      headerName: "",
      ...obj,
    });

    setSeletedIndex(-1);
  };

  const { picList } = model;
  const picLength = picList.length;

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <ByButton
            size="large"
            className="w-2/3"
            loading={loading}
            onClick={handleSubmit}
          >
            提交
          </ByButton>
        }
      >
        <View className="p-3">
          <ByCellGroup className="mb-5">
            <ByCell label="标题" {...CellProps} border={false}>
              <Input
                disabled
                className="w-full"
                placeholder={`第${params.index || 1}次日常巡检`}
              />
            </ByCell>

            <ByCell label="内容" requierd {...CellProps}>
              <Input
                placeholder="输入巡检内容"
                value={model.inspectionContent}
                onInput={(e) => setModel({ inspectionContent: e.detail.value })}
              />
            </ByCell>

            <ByCell
              label="巡检照片"
              vertical
              tip={picLength > 0 ? picLength + `张` : ""}
              {...CellProps}
            >
              <ByImageGroup
                showDelete
                urls={picList}
                onChange={(res) => setModel({ picList: res })}
                slotFooter={
                  <Uploader
                    size={140}
                    onSuccess={(res) => {
                      setModel({ picList: picList.concat(res) });
                    }}
                  />
                }
              />
            </ByCell>

            <ByCell label="业主可见" {...CellProps}>
              <Switch
                checked={model.isCanSee}
                onChange={({ detail }) => setModel({ isCanSee: detail.value })}
              />
            </ByCell>
          </ByCellGroup>

          {detailList.map((item, index) => (
            <TaskItems
              nodeId={`tast_item_node_${index}`}
              key={item._id}
              index={index}
              source={item}
              onPicker={() => setSeletedIndex(index)}
              onDelete={() => handleDeleteItem(index)}
              onChange={(data) => handleChangeItem(index, data)}
            />
          ))}

          <View className="mt-4 text-center">
            <ByButton
              size="small"
              type="error"
              variant="outline"
              className="w-1/2"
              onClick={addItem}
            >
              新增不合格项
            </ByButton>
          </View>
        </View>
      </Page>

      <PageContainer
        show={selectedIndex > -1}
        onAfterLeave={() => setSeletedIndex(-1)}
      >
        <PopupMember
          type={["project", "supplier"]}
          intentCustomerId={intentCustomerId}
          onCancel={() => setSeletedIndex(-1)}
          onConfirm={handleConfirm}
        />
      </PageContainer>
    </>
  );
};
